import { reqGetUserInfo, reqLogin, reqGetUserDataIlById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  state() {
    return {
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(state.token)
    },
    setUserInfo(state, newInfo) {
      state.userInfo = newInfo
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  getters: {

  },
  actions: {
    async login(context, loginFrom) {
      // 结果res.data.data data:token 起别名
      // const { data: { data: token }} = await reqLogin(loginFrom)
      const res = await reqLogin(loginFrom)
      const token = res.data
      console.log(token)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const { data: data1 } = await reqGetUserInfo()
      console.log(data1)
      // 发送获取员工信息请求
      const { data: data2 } = await reqGetUserDataIlById(data1.userId)
      console.log('员工基本数据', data2)
      // 合并两个data
      const res = { ...data1, ...data2 }
      context.commit('setUserInfo', res)

      return res
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  },
  namespaced: true
}
